<template>
  <div class="setting-container">
    <div class="app-container">
      <!-- 卡片组件 -->
      <el-card class="box-card">
        <!-- 使用 Tabs 组件完成标签页布局 -->
        <el-tabs v-model="activeName" @tab-click="tabClickFn">
          <!-- 角色管理页 -->
          <el-tab-pane label="角色管理" name="first" class="tab-pane">
            <!-- 新增角色按钮 独占一行 -->
            <el-row style="height:60px">
              <el-button icon="el-icon-plus" size="small" type="primary" @click="addRole">新增角色</el-button>
            </el-row>
            <!-- 使用 Table 组件实现用户角色的渲染 -->
            <el-table border style="width: 100%" :data="rolesList">
              <el-table-column type="index" label="序号" width="120" />
              <el-table-column label="角色名" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="setRoles(scope.row)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRoles(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRoles(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination :current-page="query.page" :page-sizes="[10, 15, 20, 25]" :page-size="query.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </el-tab-pane>
          <!-- 公司信息页 -->
          <el-tab-pane label="公司信息" name="second" class="tab-pane">
            <el-alert title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改" type="info" show-icon :closable="false" />
            <el-form :model="formData" label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="formData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="formData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 新增弹窗 -->
      <el-dialog :title="dialogTitle" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="showDialog" :show-close="false">
        <el-form ref="roleForm" :model="roleForm" :rules="roleRules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="cancleRoles">取消</el-button>
            <el-button size="small" type="primary" @click="roleSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限弹框 -->
      <el-dialog title="分配权限" :visible.sync="dialogVisible" width="50%">
        <assign-permission :dialog-visible.sync="dialogVisible" :role-id="roleId" :permission-list="permissionList" :role-ids-list="roleIdsList" @confirmPerEV="confirmPerFn" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRolesAPI, getCompanyInfoAPI, addRoleAPI, updateRoleAPI, deleteRoleAPI, getPermissionListAPI, getRoleIdListAPI, assignPermAPI } from '@/api'
import { mapGetters } from 'vuex'
import AssignPermission from './component/assignPermission.vue'
import { transTree } from '@/utils' // 处理树形控件数据方法
export default {
  components: {
    AssignPermission
  },
  data() {
    return {
      // 默认显示的页面
      activeName: 'first',
      query: {
        page: 1, // 当前页面
        pagesize: 10 // 页面显示的条数
      },
      rolesList: [], // 角色列表
      total: 0, // 角色数据总条数
      formData: {},
      showDialog: false, // 控制弹框的隐藏和展示
      dialogTitle: '', // 弹窗标题
      // 添加角色
      roleForm: {
        name: '',
        description: ''
      },
      // 添加角色验证
      roleRules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      isEdit: false, // 是否是编辑
      editId: '', // 编辑的id
      dialogVisible: false, // 分配权限弹窗
      roleId: '', // 当前点击项的id
      permissionList: [], // 权限列表
      roleIdsList: [] // 当前角色的权限
    }
  },
  computed: {
    ...mapGetters(['companyId']) // 获取当前登录用户的id
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const res = await getRolesAPI(this.query)
      // 如果得到的结果数组长度为0,并且不是第一页的时候,回到前一页重新发请求
      if (res.data.rows.length === 0 && this.query.page > 1) {
        this.query.page-- // 回到前一页重新请求数据
        this.getRolesList()
        return
      }
      this.rolesList = res.data.rows
      this.total = res.data.total
    },
    // 获取公司信息
    async getCompanyInfoFn() {
      // 调用接口,传入id
      const res = await getCompanyInfoAPI(this.companyId)
      this.formData = res.data
    },
    // 添加角色按钮
    addRole() {
      this.dialogTitle = '添加角色'
      this.isEdit = false
      this.showDialog = true
    },
    // 弹窗取消
    cancleRoles() {
      this.showDialog = false
      // 恢复表单
      this.roleForm = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
    },
    // 弹窗确定
    roleSubmit() {
      this.$refs.roleForm.validate(async valid => {
        if (!valid) return
        if (this.isEdit) {
          // 编辑
          // this.roleForm.id = this.editId
          const res = await updateRoleAPI({
            id: this.editId,
            ...this.roleForm // 展开对象,合并为1个对象
          })
          this.$message.success(res.message)
          this.getRolesList()
        } else {
          // 添加角色
          const res = await addRoleAPI(this.roleForm)
          this.$message.success(res.message)
          this.getRolesList()
        }
        this.showDialog = false // 关闭弹窗
        // 恢复表单
        this.roleForm = {
          name: '',
          description: ''
        }
        this.$refs.roleForm.resetFields()
      })
    },
    // tab栏切换事件
    tabClickFn() {
      // 切换到公司信息栏的时候,获取公司信息
      if (this.activeName === 'second') {
        this.getCompanyInfoFn()
      }
    },
    // 每页显示的条数发生改变时触发
    handleSizeChange(pagesize) {
      this.query.pagesize = pagesize
      this.getRolesList()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(page) {
      this.query.page = page
      this.getRolesList()
    },

    // 分配权限
    async setRoles(dataObj) {
      // 先清空权限数组,因为打开时数组还保存着上一个的数据,会出现数据闪现的问题
      this.roleIdsList = []
      this.roleId = dataObj.id // 保存当前点击项的id
      const res = await getPermissionListAPI() // 获取权限列表
      this.permissionList = transTree(res.data, '0') // 处理树形控件数据
      // 根据id获取当前角色详情
      const resp = await getRoleIdListAPI(dataObj.id)
      // 保存当前角色的权限
      this.roleIdsList = resp.data.permIds
      this.dialogVisible = true
    },

    // 保存权限 -> 弹窗确定按钮
    async confirmPerFn(dataObj) {
      // 接收数据 调用接口
      const res = await assignPermAPI(dataObj)
      this.dialogVisible = false
      this.$message.success(res.message)
    },

    // 编辑角色
    editRoles(data) {
      this.dialogTitle = '编辑角色'
      this.isEdit = true
      this.showDialog = true
      this.roleForm.name = data.name
      this.roleForm.description = data.description
      this.editId = data.id
    },

    // 删除角色
    delRoles(data) {
      this.$confirm('此操作不可恢复,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const res = await deleteRoleAPI(data.id)
          this.getRolesList()
          this.$message.success(res.message)
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.box-card {
  padding: 10px 30px;
}

.tab-pane {
  padding: 20px;
}

.el-pagination {
  text-align: center;
  margin-top: 20px;
}
</style>
